<?php
import("ORG.Util.Function");
import("@.Org.Utils");

class ArticlecatAction extends CommonAction {
	
	public function _initialize(){
		parent::_initialize();				
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];		
		//language
		$lang            =    L($action);  		
		$manage          =    L('manage');
		
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);
	}
	/**
	 * 构造函数
	 * Enter description here ... 
	 */ 
	public function __construct(){
		parent::__construct(); //must have
		$user_name          =   $_SESSION['user_name'];
		$this->assign("username",$user_name);
		$this->assign("web_title","后台管理");
	}
	
	/**
	 * 文章分类列表
	 * Enter description here ...
	 */
	public function articlecat_list(){
		$ArtCat        =     new Model('ArticleCat');
			
		$datas         =     $ArtCat->select();	
		// 分级不同，缩进不同	
		$datas         =     $this->catsort($datas,0,0);	
		foreach($datas as $n=>$v){
			$v['cat_name']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['cat_name'];
			$articleCatList[] =    $v;
		}		
		$this->assign("articleCatList",$articleCatList);
		$this->display('Article:articlecat_list');
	}
	
	/**
	 * 添加文章分类
	 * Enter description here ...
	 */
	public function add_articlecat(){
		$ArtCat        =    new Model('ArticleCat');
		// 编辑分类
		$datas         =    $ArtCat->field("cat_id,cat_name,parent_id")->select();	
		$datas         =    $this->catsort($datas,0,0);	
		//Indent
		$articleCatList = array();
		foreach($datas as $n=>$v){
			$v['cat_name']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['cat_name'];
			$articleCatList[] =    $v;
		}			
		$this->assign("article_cat_list" 		,$articleCatList);
		$this->assign("act",					'add_articlecat'); // 操作方式
		$this->display('Article:add_articlecat');
	}
	
	/**
	 * 处理添加文章分类
	 * Enter description here ...
	 */
	public function add_articlecat_ok(){
		$datas	=	array();
	    //检查分类名是否重复
	    $is_only = 	Utils::is_only('article_cat','cat_name', $_POST['cat_name']);			
	    if (!$is_only){
	        $this->error("文章分类名--" . $_POST['cat_name'] . "--不能重复");
	    }
	
	    $cat_type 		= 	1;
	    if ($_POST['parent_id'] > 0){
	        $sql 		=	"SELECT cat_type FROM ybr_article_cat  WHERE cat_id = '$_POST[parent_id]'";
	        $p_cat_type = 	M('ArticleCat')->where("cat_id = '$_POST[parent_id]'")->getField("cat_type");
	        if ($p_cat_type == 2 || $p_cat_type == 3 || $p_cat_type == 5){
	            $this->error("系统保留分类,不允许添加子分类");
	        }
	        else if ($p_cat_type == 4){
	            $cat_type = 5;
	        }
	    }
	    
	    $datas['cat_type']		=	$cat_type;
	    $datas['cat_name']		=	$_POST['cat_name'];
	    $datas['cat_desc']		=	$_POST['cat_desc'];
	    $datas['keywords']		=	$_POST['keywords'];
	    $datas['sort_order']	=	$_POST['sort_order'];
	    $datas['show_in_nav']	=	$_POST['show_in_nav'];
	    $datas['parent_id']		=	$_POST['parent_id'];
	   
		M('ArticleCat')->add($datas);
//	    if($_POST['show_in_nav'] == 1){
//	        $vieworder = $db->getOne("SELECT max(vieworder) FROM ". $ecs->table('nav') . " WHERE type = 'middle'");
//	        $vieworder += 2;
//	        //显示在自定义导航栏中
//	        $sql = "INSERT INTO " . $ecs->table('nav') . " (name,ctype,cid,ifshow,vieworder,opennew,url,type) VALUES('" . $_POST['cat_name'] . "', 'a', '" . $db->insert_id() . "','1','$vieworder','0', '" . build_uri('article_cat', array('acid'=> $db->insert_id()), $_POST['cat_name']) . "','middle')";
//	        $db->query($sql);
//	    }
		$this->success("操作成功",U('articlecat/add_articlecat'));
	}
	
	/**
	 * 修改文章分类
	 * Enter description here ...
	 */
	public function mod_articlecat(){	
		$id 			=	intval($_GET['cat_id']);
		
		$ArtCat      	=    new Model('ArticleCat');		
		$cat_info		=	$ArtCat->where("cat_id = '{$id}'")->find();
		
		// 编辑分类
		$datas         	=    $ArtCat->field("cat_id,cat_name,parent_id")->select();	
		$datas         	=    $this->catsort($datas,0,0);
		//Indent
		$articleCatList = array();
		foreach($datas as $n=>$v){
			$v['cat_name']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['cat_name'];
			$articleCatList[] =    $v;
		}		
		
		$this->assign("article_cat_list" 	,$articleCatList);
		$this->assign("cat_info"  			,$cat_info); 	// 修改分类信息
		$this->assign("act"					,'mod_articlecat'); // 操作方式
		$this->display('Article:add_articlecat');
	}
	
	/**
	 * 处理修改文章分类
	 * Enter description here ...
	 */
	public function mod_articlecat_ok(){
		
		$ArticleCatModel			=	M('ArticleCat');
		
		$cat_id						=	empty($_POST['id']) ? 0 : $_POST['id'];
		
		if(empty($cat_id)){
			$this->redirect('/articlecat/articlecat_list', null,2,'invalid param,please check the param...');
		}
		
		// check the same cat_name
		$datas['cat_name']			=	trim($_POST['cat_name']);
		
	    /*$is_only 					= 	Utils::is_only('article_cat','cat_name', $_POST['cat_name']);			
	    if (!$is_only){
	        $this->error("文章分类名--" . $_POST['cat_name'] . "--不能重复");
	    }*/
		
		$cat_type 					= 	1;
	    if ($_POST['parent_id'] > 0){
	        $sql 					=	"SELECT cat_type FROM ybr_article_cat  WHERE cat_id = '$_POST[parent_id]'";
	        $p_cat_type 			= 	M('ArticleCat')->where("cat_id = '$_POST[parent_id]'")->getField("cat_type");
	        if ($p_cat_type == 2 || $p_cat_type == 3 || $p_cat_type == 5){
	            $this->error("系统保留分类,不允许添加子分类");
	        }
	        else if ($p_cat_type == 4){
	            $cat_type = 5;
	        }
	    }
	    	    
		$datas['parent_id']			=	empty($_POST['parent_id']) ? 0 : $_POST['parent_id'];
		$datas['sort_order']		=	empty($_POST['sort_order']) ? 0 : $_POST['sort_order'];
		$datas['show_in_nav']		=	empty($_POST['show_in_nav']) ? 0 : $_POST['show_in_nav'];
		$datas['keywords']			=	$_POST['keywords'];
		$datas['cat_desc']			=	$_POST['cat_desc'];	
		$datas['cat_type']			=	$cat_type;	
				
		$ArticleCatModel->where("cat_id = '{$cat_id}'")->save($datas);			
		
		$this->redirect('/articlecat/articlecat_list', null,2,'处理成功,正在为您跳转...');	
	}
	
	/**
	 * 删除文章分类
	 * Enter description here ...
	 */
	public function remove_articlecat_ok(){
		$cat_id		=	intval($_GET['cat_id']);
		$cat_type	=	M('ArticleCat')->where("cat_id = '$cat_id'")->getField("cat_type");
	    if($cat_type == 2 || $cat_type == 3 || $cat_type ==4){
	        // 系统保留分类，不能删除
	       	$this->error("系统保留分类,不能删除");
	    }
	    
	    $result		=	M('ArticleCat')->field("COUNT(*) count")->where("parent_id = '$cat_id'")->select();	  
		
	    if ($result[0]['count'] > 0){
	        // 还有子分类，不能删除
	       	$this->error("还有子分类，不能删除");
	    }
	
	    // 非空文章的分类不允许删除 
	    $result		=	M('Article')->field("COUNT(*) count")->where("cat_id = '$cat_id'")->select();
	    
	    if ($result[0]['count'] > 0){
	       // $this->error("还有子分类，不能删除");
	    }
	    else{
	        M('ArticleCat')->where("cat_id = '{$cat_id}'")->delete();
	        //$db->query("DELETE FROM " . $ecs->table('nav') . "WHERE  ctype = 'a' AND cid = '$id' AND type = 'middle'");
	    }
	    $this->success("操作成功",U('article/articlecat_list'));
	}	
	
	/**
	 * ArticleCatAjaxTable
	 * @param	id	int
	 */
	public function articleCatAjaxTable(){
		$ArticleCatModel    =    new Model('ArticleCat');
		$ArticleModel    	=    new Model('Article');
		$act                =    $_POST['action'];
		
		switch($act){
			case 'del':				
				$id       				=    $_POST['id'];
				/*判断分类下有无子分类*/
				$is_exsists_childcat	=	$ArticleCatModel->where("parent_id = '{$id}'")->find();
				
				if(!empty($is_exsists_childcat)){
					$this->ajaxReturn(0,'该分类下存在子分类',1);
				}				
				/*判断该分类下有无文章*/
				$is_exsists_article		=	$ArticleModel->where("cat_id ='{$id}'")->find();	
				if(!empty($is_exsists_article)){
					$this->ajaxReturn(0,'该分类下有文章',1);
				}
				
				$result   				=    $ArticleCatModel->where("cat_id='{$id}'")->delete();
		
				if($result){
					$this->ajaxReturn($result,"删除成功",1);
				}else{
					$this->ajaxReturn($result,"删除失败",0);
				}
				break;
			case 'change':
				$field         =    $_POST['field'];
				$value         =    $_POST['val'];
				$id            =    $_POST['id'];
				$data[$field]  =    $value;
				//Save Data
				$result        =    $ArticleCatModel->where("id=$id")->save($data);
		
				if($result){
					$this->ajaxReturn($value,"修改成功",1);
				}
				else{
					$this->ajaxReturn(null,"修改成功",0);
				}
				break;
		}
	}
	
	/**
	 * 排序
	 * @param unknown $arr
	 * @param number $parent_id
	 * @param number $lev
	 * @return multitype:number
	 */
	public function catsort($arr,$parent_id = 0,$lev = 1){
		static $list = array();
		foreach ($arr as $v){
			if($v['parent_id'] == $parent_id){
				$v['lev']  = $lev;
				$list[]    = $v;
				$this->catsort($arr,$v['cat_id'],$lev +1);
			}
		}
		return $list;
	}
	
}